package site.higgs.limiter.ratelimiter.support.redis;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import site.higgs.limiter.ratelimiter.RateLimiter;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;


/**
 * Created by caocg on 2018/9/25.
 */
public class RedisRateLimiter extends RateLimiter {


    private RedissonClient redisson;

    private String name;

    public RedisRateLimiter(String name, RedissonClient redisson) {
        this.redisson = redisson;
        this.name = name;
    }


    @Override
    public boolean acquire(Object key, double pps,long intervalTime, RateIntervalUnit ppsTimeUnit) {
        RRateLimiter rRateLimiter = redisson.getRateLimiter(key.toString());
        boolean flag = rRateLimiter.trySetRate(RateType.OVERALL, new Double(pps).longValue(), intervalTime, ppsTimeUnit);
        if (flag) {
            ChronoUnit unit;
            if (ppsTimeUnit == RateIntervalUnit.MINUTES) {
                unit = ChronoUnit.MINUTES;
            } else if (ppsTimeUnit == RateIntervalUnit.HOURS) {
                unit = ChronoUnit.HOURS;
            } else if (ppsTimeUnit == RateIntervalUnit.DAYS) {
                unit = ChronoUnit.DAYS;
            } else {
                unit = ChronoUnit.SECONDS;
            }
            //设置过期时间
            rRateLimiter.expire(Duration.of(intervalTime,unit));
        }
        return rRateLimiter.tryAcquire();
    }

    @Override
    public String getName() {
        return this.name;
    }
}
